package com.wasai.service;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.wasai.dao.UserDAO;
import com.wasai.domain.User;
import com.wasai.util.gravatar.Gravatar;
import com.wasai.util.gravatar.GravatarDefaultImage;

@Service
@Transactional(readOnly = true)
public class UserService {
	private static final Logger log = LoggerFactory
			.getLogger(UserService.class);

	@Resource
	private UserDAO userDAO;

	public boolean checkLoginUser(User user) {
		log.debug("checkLoginUser");
		if (null == user) {
			return false;
		}
		final DetachedCriteria dc = DetachedCriteria.forClass(User.class);
		dc.add(Restrictions.eq("email", user.getEmail())).add(
				Restrictions.eq("password",
						DigestUtils.md5Hex(user.getPassword())));
		User foundUser = userDAO.getByCriteria(dc);
		if (foundUser != null) {
			return true;
		} else {
			return false;
		}
	}

	public User getUserByEmail(String email) {
		log.debug("getUserByEmail");
		final DetachedCriteria dc = DetachedCriteria.forClass(User.class);
		dc.add(Restrictions.eq("email", email));
		User foundUser = userDAO.getByCriteria(dc);
		return foundUser;
	}

	public User getUserById(int userid) {
		log.debug("getUserById");
		final User user = this.userDAO.getById(User.class, userid);
		return user;
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public boolean signup(User user) {
		log.debug("singup");
		if (user == null || user.getEmail() == null) {
			return false;
		}
		User existUser = this.getUserByEmail(user.getEmail());
		if (existUser != null)
			return false;
		user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		final Gravatar gravatar = new Gravatar();
		gravatar.setDefaultImage(GravatarDefaultImage.IDENTICON);
		user.setAvatar(gravatar.getUrl(user.getEmail()));
		this.userDAO.save(user);
		return true;
	}

}
